<template>
  <view class="device-detail">
    <!-- 远程控制 -->
    <view class="control-panel">
      <text class="panel-title">远程控制</text>
      <view class="device-preview">
        <image
          :src="deviceInfo.imageUrl"
          mode="aspectFit"
          class="preview-image"
        />
        <view class="control-buttons">
          <!-- 泵站控制按钮 -->
          <template v-if="isPump">
            <view class="control-btn online" @click="handleControl('start')">
              <image src="@/static/images/start-btn.png" mode="aspectFit" />
              <text>泵站启动</text>
            </view>
            <view class="control-btn offline" @click="handleControl('stop')">
              <image src="@/static/images/close-btn.png" mode="aspectFit" />
              <text>泵站关闭</text>
            </view>
            <view class="control-btn" @click="handleControl('monitor')">
              <image
                src="@/static/images/surveillance-btn.png"
                mode="aspectFit"
              />
              <text>视频监控</text>
            </view>
          </template>

          <!-- 闸门控制按钮 -->
          <template v-if="deviceInfo.type === '2'">
            <view class="control-btn online" @click="handleControl('up')">
              <image src="@/static/images/rise-btn.png" mode="aspectFit" />
              <text>闸门上升</text>
            </view>
            <view class="control-btn online" @click="handleControl('down')">
              <image src="@/static/images/descend-btn.png" mode="aspectFit" />
              <text>闸门下降</text>
            </view>
            <view class="control-btn offline" @click="handleControl('stop')">
              <image src="@/static/images/stop-btn.png" mode="aspectFit" />
              <text>闸门停止</text>
            </view>
          </template>

          <!-- 阀门控制按钮 -->
          <template v-if="deviceInfo.type === '4'">
            <view class="control-btn online" @click="handleControl('open')">
              <image src="@/static/images/start-btn.png" mode="aspectFit" />
              <text>启动阀门</text>
            </view>
            <view class="control-btn offline" @click="handleControl('close')">
              <image src="@/static/images/stop-btn.png" mode="aspectFit" />
              <text>关闭阀门</text>
            </view>
            <view class="control-btn offline" @click="handleControl('stop')">
              <image src="@/static/images/close-btn.png" mode="aspectFit" />
              <text>阀门关闭</text>
            </view>
          </template>
        </view>
      </view>
    </view>

    <!-- 设备信息 -->
    <view class="info-panel">
      <text class="panel-title">{{ infoTitle }}</text>
      <view class="info-list">
        <view class="info-item">
          <text class="label">名称：</text>
          <text class="value">{{ deviceInfo.pumpName || "--" }}</text>
        </view>
        <view class="info-item">
          <text class="label">尺寸：</text>
          <text class="value">{{ deviceInfo.size || "--" }}m</text>
        </view>
        <view class="info-item" v-if="isPump">
          <text class="label">泵型：</text>
          <text class="value">{{ deviceInfo.model || "--" }}</text>
        </view>
        <view class="info-item">
          <text class="label">编号：</text>
          <text class="value">{{ deviceInfo.pumpIdLabel || "--" }}</text>
        </view>
        <view class="info-item" v-if="isPump">
          <text class="label">流量：</text>
          <text class="value">{{ deviceInfo.flow || "--" }}m³/h</text>
        </view>
        <view class="info-item" v-if="isPump">
          <text class="label">扬程：</text>
          <text class="value">{{ deviceInfo.lift || "--" }}m</text>
        </view>
        <view class="info-item">
          <text class="label">功率：</text>
          <text class="value">{{ deviceInfo.power || "--" }}kw</text>
        </view>
        <view class="info-item">
          <text class="label">安装日期：</text>
          <text class="value">{{ deviceInfo.installDate || "--" }}</text>
        </view>
        <view class="info-item">
          <text class="label">安装人员：</text>
          <text class="value">{{ deviceInfo.installPerson || "--" }}</text>
        </view>
        <view class="info-item">
          <text class="label">售后电话：</text>
          <text class="value">{{ deviceInfo.contact || "--" }}</text>
        </view>
      </view>
    </view>

    <!-- 实时参数 -->
    <view class="params-panel">
      <text class="panel-title">实时参数</text>
      <view class="params-grid" >
        <view class="param-group param-group1" v-if="isPump">
          <text class="param-title">累计用电量</text>
          <text class="param-unit">(kw.h)</text>
          <text class="param-value">{{
            realTimeData.sumUseElectricity || "--"
          }}</text>
        </view>
        <view class="param-group param-group2" v-if="isPump">
          <text class="param-title">累计用水量</text>
          <text class="param-unit">(m³)</text>
          <text class="param-value">{{
            realTimeData.sumUseWater || "--"
          }}</text>
        </view>
        <view class="param-group param-group3" v-if="isPump">
          <text class="param-title">累计运行时间</text>
          <text class="param-unit">(h)</text>
          <text class="param-value">{{
            realTimeData.sumRunTimeHours || "--"
          }}</text>
        </view>
        <view class="param-item">
          <image src="@/static/images/temperature.png" mode="aspectFit" />
          <text class="param-label">温度(℃)</text>
          <text class="param-value">{{
            realTimeData.temperature || "--"
          }}</text>
        </view>
        <view class="param-item">
          <image src="@/static/images/humidity.png" mode="aspectFit" />
          <text class="param-label">湿度(%)</text>
          <text class="param-value">{{ realTimeData.humidity || "--" }}</text>
        </view>
        <view class="param-item" v-if="isPump">
          <image src="@/static/images/flow.png" mode="aspectFit" />
          <text class="param-label">流量(m³/h)</text>
          <text class="param-value">{{ realTimeData.flow || "--" }}</text>
        </view>
		<view class="param-item" v-if="!isPump">
		  <image src="@/static/images/flow.png" mode="aspectFit" />
		  <text class="param-label">剩余电量(%))</text>
		  <text class="param-value">{{ realTimeData.batteryCapacity || "--" }}</text>
		</view>
        <view class="param-item">
          <image src="@/static/images/voltage.png" mode="aspectFit" />
          <text class="param-label">电压(V)</text>
          <text class="param-value">{{ realTimeData.voltage || "--" }}</text>
        </view>
        <view class="param-item">
          <image src="@/static/images/current.png" mode="aspectFit" />
          <text class="param-label">电流(A)</text>
          <text class="param-value">{{ realTimeData.current || "--" }}</text>
        </view>
        <view class="param-item" v-if="isPump">
          <image src="@/static/images/electricity.png" mode="aspectFit" />
          <text class="param-label">用电量(kw.h)</text>
          <text class="param-value">{{
            realTimeData.useElectricity || "--"
          }}</text>
        </view>
		<view class="param-item" v-if="isPump">
		  <image src="@/static/images/control-mode.png" mode="aspectFit" />
		  <text>控制模式</text>
		  <text class="status-value">{{
		    realTimeData.mode
		      ? realTimeData.mode == "1"
		        ? "自动"
		        : "手动"
		      : "--"
		  }}</text>
		</view>
		<view class="param-item">
		  <image src="@/static/images/status.png" mode="aspectFit" />
		  <text>运行状态</text>
		  <text class="status-value">{{
		    formatStatus(realTimeData.deviceStatus)
		  }}</text>
		</view>
		<view class="param-item">
		  <image src="@/static/images/alarm.png" mode="aspectFit" />
		  <text>故障报警</text>
		  <text class="status-value">{{
		    realTimeData.alarmStatus == "1" ? "有" : "无"
		  }}</text>
		</view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getDeviceBaseData } from "@/api/smartMonitoring";
import { pictureUrl, formatStatus } from "@/utils/index";
import { getRealTimeData, startPump, endPump } from "@/api/index";

type DeviceType = "1" | "2" | "4"|"11"|"12";

interface DeviceInfo {
  pumpId: string;
  pumpName: string;
  imageUrl: string;
  size: string;
  model?: string;
  pumpIdLabel: string;
  flow?: string;
  lift?: string;
  power: string;
  installDate: string;
  installPerson: string;
  contact: string;
  pumpState: string;
  type: DeviceType;
  [key: string]: any;
}

const pumpId = ref("");
const deviceInfo = ref<DeviceInfo>({
  pumpId: "",
  pumpName: "",
  imageUrl: "",
  size: "",
  model: "",
  pumpIdLabel: "",
  flow: "",
  lift: "",
  power: "",
  installDate: "",
  installPerson: "",
  contact: "",
  pumpState: "",
  type: "1",
});

// 设备图片
// const deviceImage = computed(() => {
//   const imageMap: Record<DeviceType, string> = {
//     1: "/static/images/pump.png",
//     2: "/static/images/gate.png",
//     4: "/static/images/valve.png",
//   };
//   return imageMap[deviceType.value];
// });

const infoTitle = computed(() => {
  return ["1","11","12"].includes(deviceInfo.value.type)
    ? "泵站详情"
    : deviceInfo.value.type === "2"
    ? "闸门详情"
    : "阀门详情";
});
const isPump=computed(()=>{
	return ["1","11","12"].includes(deviceInfo.value.type)
})
interface realData {
  sumUseElectricity?: string;
  sumRunTimeHours?: string;
  sumUseWater?: string;
  temperature?: string;
  humidity?: string;
  flow?: string;
  current?: string;
  voltage?: string;
  alarmStatus?: string;
  deviceStatus: string;
  mode?: string;
  useElectricity?: string;
  [key: string]: any;
}
const realTimeData = ref<realData>({
  alarmStatus: "",
  deviceStatus: "",
});
//实时数据
const queryRealTimeData = () => {
  getRealTimeData({ pumpId: pumpId.value }).then((res) => {
    let result = res.data;
    if (result) {
      realTimeData.value = result;
      //   Object.assign(pumpRealInfo, {
      //     ...result,
      //     deviceStatus: formatStatus(result.deviceStatus),
      //     alarmStatus: result.alarmStatus == 1 ? "有" : "无",
      //     mode: result.mode == 1 ? "自动" : "手动",
      //   });
    }
  });
};
// 获取设备详情
const getDeviceDetail = async () => {
  try {
    const res = await getDeviceBaseData({ pumpId: pumpId.value });
    if (res.code == "2000") {
      deviceInfo.value = {
        ...res.data,
        imageUrl: res.data.imageUrl.replace("E:", pictureUrl),
      };
      if (res.data.pumpState === "3") {
        //运行中状态才能获取到实时参数
        queryRealTimeData();
      } else {
        realTimeData.value.deviceStatus = deviceInfo.value.pumpState;
      }
    }
  } catch (error) {
    uni.showToast({
      title: "获取设备详情失败",
      icon: "none",
    });
  }
};

// 控制按钮处理
const handleControl = (action: string) => {
  // TODO: 根据不同action调用对应的控制接口
  switch (action) {
    case "monitor":
      uni.navigateTo({
        url: `/pages/seedlingMonitor/index?address=${deviceInfo.value.address}&type=${deviceInfo.value.type}&deviceId=${deviceInfo.value.deviceId}`,
      });
      break;
    case "start": //开启泵站
      uni.showModal({
        title: "提示",
        content: "确认启动？",
        success: (result) => {
          if (result.confirm) {
            startPump({ deviceId: pumpId.value }).then((res) => {
              if (res.code === "2000") {
                uni.showToast({
                  title: "启动成功",
                  icon: "success",
                });
              } else {
                uni.showToast({
                  title: "启动失败",
                  icon: "none",
                });
              }
            });
          }
        },
      });
      break;
    case "stop": //泵站，闸门关闭
      uni.showModal({
        title: "提示",
        content: "确认停止当前设备?",
        success: (result) => {
          if (result.confirm) {
            endPump({ deviceId: pumpId.value }).then((res) => {
              if (res.code === "2000") {
                uni.showToast({
                  title: "操作成功",
                  icon: "success",
                });
              } else {
                uni.showToast({
                  title: "操做失败",
                  icon: "none",
                });
              }
            });
          } else if (result.cancel) {
            console.log("用户点击取消");
          }
        },
      });
      break;

    case "up": //闸门上升
      uni.showModal({
        title: "提示",
        content: "确认启动？",
        success: (result) => {
          if (result.confirm) {
            startPump({ deviceId: pumpId.value }).then((res) => {
              if (res.code === "2000") {
                uni.showToast({
                  title: "启动成功",
                  icon: "success",
                });
              } else {
                uni.showToast({
                  title: "启动失败",
                  icon: "none",
                });
              }
            });
          }
        },
      });
      break;

    case "down":
      uni.showToast({
        title: "功能开发中",
        icon: "none",
      });
      break;
    case "gateStop":
      uni.showToast({
        title: "功能开发中",
        icon: "none",
      });
      break;
    case "open":
      uni.showToast({
        title: "功能开发中",
        icon: "none",
      });
      break;
    case "close":
      uni.showToast({
        title: "功能开发中",
        icon: "none",
      });
      break;
    default:
      uni.showToast({
        title: "功能开发中",
      });
      break;
  }
};

onLoad((options: Record<string, string> | undefined) => {
  if (options?.id) {
    pumpId.value = options.id;
  }
  getDeviceDetail();
});
</script>

<style lang="scss" scoped>
.device-detail {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;

  .control-panel,
  .info-panel,
  .params-panel {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;
  }

  .panel-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }

  .device-preview {
    display: flex;
    flex-direction: row;
    align-items: center;

    .preview-image {
      width: 182rpx;
      height: 182rpx;
      border-radius: 16rpx;
    }

    .control-buttons {
      display: flex;
      justify-content: space-around;
      width: 100%;

      .control-btn {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20rpx;

        image {
          width: 88rpx;
          height: 88rpx;
          margin-bottom: 10rpx;
        }

        text {
          font-size: 24rpx;
          color: #333;
        }

        &.online {
          color: #52c41a;
          image {
            tint-color: #52c41a;
          }
        }

        &.offline {
          color: #ff4d4f;
          image {
            tint-color: #ff4d4f;
          }
        }
      }
    }
  }

  .info-list {
    .info-item {
      display: flex;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .label {
        width: 160rpx;
        color: #666;
        font-size: 28rpx;
      }

      .value {
        flex: 1;
        color: #333;
        font-size: 28rpx;
      }
    }
  }

  .params-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
    overflow: hidden; // 防止内容溢出容器
    margin-bottom: 20rpx;
    margin-top: 20rpx;

    .param-group {
      //   background: linear-gradient(135deg, #a18cd1 0%, #fbc2eb 100%);
      //   width: 198rpx;
      height: 126rpx;
      border-radius: 16rpx;
      padding: 15rpx;
      text-align: center;
      color: #fff;
      display: flex;
      flex-direction: column;
      .param-title {
        text-align: left;
        font-size: 24rpx;
        margin-bottom: 10rpx;
      }

      .param-value {
        text-align: left;
        font-size: 36rpx;
        font-weight: bold;
        margin: 10rpx 0;
      }

      .param-unit {
        text-align: left;
        font-size: 20rpx;
      }
    }
    .param-group1 {
      background: url("@/static/images/totalElectricity-bg.png") no-repeat;
      background-size: 100% 100%;
    }
    .param-group2 {
      background: url("@/static/images/totalWater-bg.png") no-repeat;
      background-size: 100% 100%;
    }
    .param-group3 {
      background: url("@/static/images/totalTime-bg.png") no-repeat;
      background-size: 100% 100%;
    }

    .param-item {
      background: #f8f8f8;
      border-radius: 16rpx;
      padding: 20rpx;
      display: flex;
      flex-direction: column;
      align-items: center;

      image {
        width: 48rpx;
        height: 48rpx;
        margin-bottom: 10rpx;
      }

      .param-label {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 10rpx;
      }

      .param-value {
        font-size: 32rpx;
        color: #333;
        font-weight: bold;
      }
    }
  }

  .status-row {
   display: grid;
   grid-template-columns: repeat(3, 1fr);
   gap: 20rpx;
    // margin-top: 20rpx;

    .status-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20rpx;
	  background: #f8f8f8;
	  

      image {
        width: 48rpx;
        height: 48rpx;
        margin-bottom: 10rpx;
      }

      text {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 10rpx;

        &.status-value {
          color: #333;
          font-weight: bold;
        }
      }
    }
  }
}
</style>
